Skip to content

Parse each external file once in ResolverCache.loadRef - #2433

Open
MuTalKing wants to merge 1 commit into
swagger-api:masterfrom
MuTalKing:cache-parsed-tree-for-external-refs
Open

MuTalKing wants to merge 1 commit into
swagger-api:masterfrom
MuTalKing:cache-parsed-tree-for-external-refs

Conversation

@MuTalKing

Copy link
Copy Markdown

Fixes #2275

Problem

ResolverCache.loadRef caches only the text of an external file. For every $ref into that file the whole content is parsed again with DeserializationUtils.deserializeIntoTree, and then a single fragment is taken from the resulting tree. With a large shared file (a "dictionary" of fields, common definitions, etc.) referenced many times, parsing time grows as refs x file size.

Change

  • The parsed tree of an external file (together with the messages produced while parsing it) is cached per ResolverCache instance, so each file is parsed once.
  • The cached tree is never handed to the deserializers. The requested subtree is copied with deepCopy() first. Without the copy two refs into the same file can end up sharing the same ObjectNode/ArrayNode (for example in Schema#example/default), so changing one resolved model would silently change another.
  • Behaviour is otherwise unchanged: the same refs resolve to the same models, parse messages are reported as before, a missing fragment still fails with Could not find ....

Measurements

Synthetic specs: a dictionary file with 1100 small schemas, specs that $ref into it via OpenAPIV3Parser.readLocation with resolve=true. Same machine and JVM, one warm-up run, then two timed runs (ms):

case master this PR
1 spec, 500 refs to the dictionary 3763 / 3753 58 / 47
60 specs, 15 refs each (900 refs) 6828 / 6805 537 / 526

This matches the report in #2275 (a build going from 4m49s to 58s). The benchmark source is in the comments below.

Tests

New ResolverCacheExternalFileTest (7 tests, with and without validateExternalRefs):

  • a file referenced many times is parsed once (fails on master: 2 parses instead of 1);
  • the same ref still resolves to the same instance;
  • results are equal to resolution with a fresh cache;
  • two overlapping refs into the same file do not share mutable nodes (fails if deepCopy() is removed);
  • validation messages from the external file are still reported;
  • a missing fragment still fails.

mvn test for swagger-parser-v3: 703 tests (696 on master plus the 7 new ones). The only failures, OpenAPIV3ParserTest.test31SafeURLResolving and test31SafeURLResolvingWithTurnedOffSafeResolving, fail the same way on unmodified master in my environment.

loadRef cached only the text of an external file and parsed the whole
content again for every $ref into it. Cache the parsed tree (and the
messages produced while parsing) per ResolverCache instance, and
deserialize from a deepCopy() of the requested subtree so that resolved
models never share mutable nodes with the cached tree.

Fixes swagger-api#2275
@MuTalKing

Copy link
Copy Markdown
Author

Benchmark used for the numbers above (temporary TestNG test placed in modules/swagger-parser-v3/src/test/java/io/swagger/v3/parser/test/; run with mvn -pl modules/swagger-parser-v3 -am test -Dtest=TmpBenchmarkTest -Dsurefire.failIfNoSpecifiedTests=false, once on master and once with this branch):

package io.swagger.v3.parser.test;

import io.swagger.v3.parser.OpenAPIV3Parser;
import io.swagger.v3.parser.core.models.ParseOptions;
import io.swagger.v3.parser.core.models.SwaggerParseResult;
import org.testng.annotations.Test;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class TmpBenchmarkTest {

    private static final int DICTIONARY_FIELDS = 1100;

    private Path generate(int specs, int refsPerSpec) throws Exception {
        Path dir = Files.createTempDirectory("bench");
        StringBuilder dict = new StringBuilder("openapi: 3.0.1\ninfo: {title: d, version: '1'}\npaths: {}\ncomponents:\n  schemas:\n");
        for (int i = 0; i < DICTIONARY_FIELDS; i++) {
            dict.append("    Field").append(i).append(":\n")
                    .append("      type: string\n")
                    .append("      description: Dictionary field number ").append(i).append(" with a reasonably long description text\n")
                    .append("      maxLength: ").append(10 + i % 50).append("\n")
                    .append("      example: value").append(i).append("\n");
        }
        Files.write(dir.resolve("dictionary.yaml"), dict.toString().getBytes(StandardCharsets.UTF_8));
        for (int s = 0; s < specs; s++) {
            StringBuilder spec = new StringBuilder("openapi: 3.0.1\ninfo: {title: s").append(s).append(", version: '1'}\npaths:\n  /p:\n    get:\n      responses:\n        '200':\n          description: ok\n          content:\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Model'\ncomponents:\n  schemas:\n    Model:\n      type: object\n      properties:\n");
            for (int r = 0; r < refsPerSpec; r++) {
                int field = (s * 31 + r * 7) % DICTIONARY_FIELDS;
                spec.append("        f").append(r).append(":\n          $ref: 'dictionary.yaml#/components/schemas/Field").append(field).append("'\n");
            }
            Files.write(dir.resolve("spec" + s + ".yaml"), spec.toString().getBytes(StandardCharsets.UTF_8));
        }
        return dir;
    }

    private long run(Path dir, int specs) {
        ParseOptions options = new ParseOptions();
        options.setResolve(true);
        long start = System.nanoTime();
        int props = 0;
        for (int s = 0; s < specs; s++) {
            SwaggerParseResult result = new OpenAPIV3Parser().readLocation(dir.resolve("spec" + s + ".yaml").toString(), null, options);
            props += result.getOpenAPI().getComponents().getSchemas().get("Model").getProperties().size();
        }
        System.out.println("BENCH checksum props=" + props);
        return (System.nanoTime() - start) / 1_000_000;
    }

    @Test
    public void benchmark() throws Exception {
        int[][] cases = {{1, 500}, {60, 15}};
        for (int[] c : cases) {
            Path dir = generate(c[0], c[1]);
            run(dir, c[0]);
            long t1 = run(dir, c[0]);
            long t2 = run(dir, c[0]);
            System.out.println("BENCH specs=" + c[0] + " refsPerSpec=" + c[1] + " totalRefs=" + c[0] * c[1] + " ms=" + t1 + "," + t2);
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Cache the result of deserialization when loading ref

1 participant